<?php

use app\models\{Dingorxuan, Sign, Signlog, Business, Reimburs, Signexcel, Businessxq};

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

//$time时间戳
function getexcels($users = [], $time)
{
    if (date('Ym', $time) == date('Ym')) {
        $days = date('d');
    } else {
        $days = date('t', $time);
    }
    $data = [];
    $shang = [
        'i' => -1,
        'orderid' => -1,
        'key' => 0, //数组下标
        'frist' => 0, //最早的日期
        'lianxu' => 0,
        'chidao' => 0,
        'zaotui' => 0,
        'weigui' => 0,
        'queka' => 0
    ];
    //生成上月考勤
    $yearmonth = date('Ym', $time);
    $nowyearmonth =  date('Ym', time());
    $isshengcheng = 1; //是否生成记录 1生成 2不生成
    if ($yearmonth < $nowyearmonth) {
        $excel = (new Signexcel())->where(['user_id' => $users['id'], 'yeardays' => date('Y-m-01', $time)])->find();
        if (empty($excel)) {
            $isshengcheng = 2;
        } else {
            //如果数据审核通过，返回修改后的数据
            if ($excel['status'] == 2) {
                $data = json_decode($excel['newdata'], true) ?? [];
            } else {
                $data = json_decode($excel['olddata'], true) ?? [];
            }
            //更新尾款结果
            foreach ($data as $k => &$row) {
                $row['orderid'] = $row['orderid'] ?? 0;
                $row['kuayue'] = '';
                $mianji = '';
                if (!empty($row['orderid'])) {
                    $weikuan = '';
                    $address = '';
                    $business = (new Business())->where(['id' => $row['orderid']])->select();
                    foreach ($business as $bus) {
                        preg_match('/(.*?(省|自治区|特别行政区|市))?(.*?(市|自治州|地区|盟|区划))?(.*?(区|县|旗|市))/', $bus['areas'], $matches);
                        $bus['areas'] = ($matches[3] ?? '') . ($matches[5] ?? '');
                        $wk = '';
                        switch ($bus['weikuan']) {
                            case '1':
                                $wk = '未回款';
                                break;
                            case '2':
                                $wk = '部分回款';
                                break;
                            case '3':
                                $wk = '全部回款';
                                break;
                            default:
                                $wk = '未知';
                                break;
                        }
                        if ($bus['weikuanstatus'] == 2) {
                            $wk = $wk . '(待审核)';
                        }
                        if (empty($address)) {
                            $address = $bus['areas'];
                        } else {
                            $address = $address . '、' . $bus['areas'];
                        }
                        if (empty($weikuan)) {
                            $weikuan = $wk;
                        } else {
                            $weikuan = $weikuan . '、' . $wk;
                        }
                        if (empty($mianji)) {
                            $fg = '';
                        } else {
                            $fg = '、';
                        }
                        if ($bus['ordertype'] != 2 && $bus['ordertype'] != 12) {
                            if (!empty($bus['mianji']) && $bus['mianji'] == 2) {
                                $mianji = $mianji . $fg . '60-79m²';
                            }
                            if (!empty($bus['mianji']) && $bus['mianji'] == 3) {
                                $mianji = $mianji . $fg . '80m²及以上';
                            }
                        }
                        $businessxq = (new Businessxq())->where(['type' => 1, 'user_id' => $users['id'], 'orderid' => $bus['id']])->find();
                        if (!empty($businessxq)) {
                            $text_type10 = '协选';
                        }
                    }
                    $row['weikuan'] = $weikuan;
                    //判断是否跨月
                    if ($k == 0) {
                        $yearssign = (new Sign())->where(['user_id' => $users['id'], 'orderid' => $row['orderid'], 'years' => date('Ym', strtotime("-1 month", $time))])->find();
                        if (!empty($yearssign)) {
                            $row['kuayue'] = '是';
                        }
                    }
                    $row['address2'] = $address;
                    $row['areas'] = $mianji;
                }
            }
            return $data;
        }
    }
    for ($i = 1; $i <= $days; $i++) {
        if ($i < 10) {
            $yearday = date('Ym', $time) . '0' . $i;
        } else {
            $yearday = date('Ym', $time) . $i;
        }
        $sign = (new Sign())->where(['user_id' => $users['id'], 'yearday' => $yearday])->find();
        $xiu = '';
        $sign['orderid'] = $sign['orderid'] ?? -1;
        if ($sign['orderid'] == -1) {
            $xiu = '休';
        }
        if ($sign['orderid'] == 0) {
            $nqcount = (new Signlog())->where(['user_id' => $sign['user_id'], 'yearday' => $sign['yearday'], 'type' => 2])->count();
            if ($nqcount <= 0) {
                $xiu = '内勤';
            } else {
                //上班是否外勤
                $sbnqcount = (new Signlog())->order('created desc')->where(['user_id' => $sign['user_id'], 'yearday' => $sign['yearday'], 'type' => 2, 'monoraft' => 1])->count();
                if ($sbnqcount > 0) {
                    $xiu = '外勤';
                } else {
                    $xiu = '内勤';
                }
                //下班是否外勤
                $xbnqcount = (new Signlog())->order('created desc')->where(['user_id' => $sign['user_id'], 'yearday' => $sign['yearday'], 'type' => 2, 'monoraft' => 2])->count();
                if ($xbnqcount > 0 && $xiu != '外勤') {
                    $xiu = $xiu . '/外勤';
                } elseif ($xiu != '内勤') {
                    $xiu = $xiu . '/内勤';
                }
            }
        }
        $group = 0;
        $groups = "";
        $ordertype = 0;
        $business = [];
        $reimburs = [];
        $mianji = '';
        $weikuan = '';
        $kehuname = '';
        $type = '';
        $dpxx = '';
        $kuayue = '';
        $address = '';
        if (!empty($sign['orderid']) && $sign['orderid'] != -1) {
            $sign['orderid'] = explode(',', $sign['orderid']);
            $business = (new Business())->where(['id' => $sign['orderid']])->select();
            foreach ($business as $bus) {
                preg_match('/(.*?(省|自治区|特别行政区|市))?(.*?(市|自治州|地区|盟|区划))?(.*?(区|县|旗|市))/', $bus['areas'], $matches);
                $bus['areas'] = ($matches[3] ?? '') . ($matches[5] ?? '');
                if (empty($address)) {
                    $address = $bus['areas'];
                } else {
                    $address = $address . '、' . $bus['areas'];
                }
                if ($i == 1) {
                    $yearssign = (new Sign())->where(['user_id' => $users['id'], 'orderid' => $sign['orderid'], 'years' => date('Ym', strtotime("-1 month", $time))])->find();
                    if (!empty($yearssign)) {
                        if (empty($kuayue)) {
                            $kuayue = '是';
                        } else {
                            $kuayue = $kuayue . '、是';
                        }
                    }
                }
                //查询派单次数 1 一次派单 2二次派单
                $pdll_text = '';
                if ($bus['ytypes'] == 1) {
                    //查询是否派单多次
                    $haves = 0;
                    $haves2 = 0;
                    $haves = (new Business());
                    if (!empty($business['phone'])) {
                        $haves = $haves->whereOr(function ($query) use ($business) {
                            $query->where('id', '<>', $business['id'])->where(['schedule' => [1, 2, 3, 4, 5, 6, 7]])->where('phone|phone2', '=', $business['phone']);
                        });
                    } else {
                        $haves = $haves->where('id', 0);
                    }
                    if (!empty($business['phone2'])) {
                        $haves = $haves->whereOr(function ($query) use ($business) {
                            $query->where('id', '<>', $business['id'])->where(['schedule' => [1, 2, 3, 4, 5, 6, 7]])->where('phone|phone2', '=', $business['phone2']);
                        });
                    }
                    $haves = $haves->count();
                    if (!empty($business['lat']) && !empty($business['lon'])) {
                        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $business['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $business['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $business['lon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
                        $haves2 = (new Biaoji())
                            ->where(['name' => $business['name']])
                            ->where('id', '<>', $business['id'])
                            ->field('id,' . $filed)
                            ->order('dist asc');
                        $haves2 = $haves2->having('dist <= 0.1')->count();
                    }
                    $havecount = $haves + $haves2;
                    if ($havecount > 0) {
                        $pdll_text = '一单两派';
                    }
                } else {
                    $pdll_text = config()["config"]['ytypes'][$bus['ytypes']] ?? '';
                }
                if (!empty($pdll_text)) {
                    $pdll_text = '(' . $pdll_text . ')';
                }
                if (empty($kehuname)) {
                    $kehuname = trim($bus['name'] ?? '') . $pdll_text;
                } else {
                    $kehuname = $kehuname . '、' . trim($bus['name'] ?? '') . $pdll_text;
                }
                $dpxx_text = config()["config"]['ytypeslist'][$bus['ytypeslist']] ?? '';
                if (empty($dpxx)) {
                    $dpxx = $dpxx_text;
                } else {
                    $dpxx = $dpxx . '、' . $dpxx_text;
                }
                $groupsname = config()["config"]['typeex'][$bus['type']] ?? '';
                if (empty($groups)) {
                    $groups = $groupsname;
                } else {
                    $groups = $groups . '、' . $groupsname;
                }
                if (empty($mianji)) {
                    $fg = '';
                } else {
                    $fg = '、';
                }
                //报销记录
                if ($bus['ordertype'] != 2 && $bus['ordertype'] != 12) {
                    // if (!empty($bus['mianji']) && $bus['mianji'] == 1) {
                    //     $mianji = $mianji . $fg . '低于60m²';
                    // }
                    if (!empty($bus['mianji']) && $bus['mianji'] == 2) {
                        $mianji = $mianji . $fg . '60-79m²';
                    }
                    if (!empty($bus['mianji']) && $bus['mianji'] == 3) {
                        $mianji = $mianji . $fg . '80m²及以上';
                    }
                }
                $reimburs = (new Reimburs())->order(['status' => 'desc', 'jobtype' => 'desc'])->where(['user_id' => $users['id'], 'orderid' => $bus['id'], 'status' => [1, 2]])->order('id desc')->find();
                if (!empty($reimburs)) {
                    $dingzhuanxuan = (new Dingorxuan())->where(['status' => 2, 'orderid' => $bus['id']])->find();
                    if (!empty($dingzhuanxuan)) {
                        $text_type10 = '定转选';
                    } else {
                        $text_type10 = trim(config()["config"]['ordertype'][$reimburs['jobtype']] ?? '');
                    }
                    $businessxq = (new Businessxq())->where(['type' => 1, 'user_id' => $users['id'], 'orderid' => $bus['id']])->find();
                    if (!empty($businessxq)) {
                        $text_type10 = '协选';
                    }
                    if (empty($type)) {
                        $type = $text_type10;
                    } else {
                        $type = $type . $fg . $text_type10;
                    }
                }
                if ($bus['ordertype'] != 2 && $bus['ordertype'] != 12) {
                    // if (!empty($reimburs) && $reimburs['mianji'] == 4 && empty($mianji)) {
                    //     $mianji = $mianji . $fg . '低于60m²';
                    // }
                    if (!empty($reimburs) && $reimburs['mianji'] == 3 && empty($mianji)) {
                        $mianji = $mianji . $fg . '60-79m²';
                    }
                    if (!empty($reimburs) && $reimburs['mianji'] == 2 && empty($mianji)) {
                        $mianji = $mianji . $fg . '80m²及以上';
                    }
                    if (!empty($reimburs) && $reimburs['mianji'] == 1 && empty($mianji)) {
                        $mianji = $mianji . $fg . '80m²以下';
                    }
                }
                $wk = '';
                switch ($bus['weikuan']) {
                    case '1':
                        $wk = '未回款';
                        break;
                    case '2':
                        $wk = '部分回款';
                        break;
                    case '3':
                        $wk = '全部回款';
                        break;
                    default:
                        $wk = '未知';
                        break;
                }
                if ($bus['weikuanstatus'] == 2) {
                    $wk = $wk . '(待审核)';
                }
                if (empty($weikuan)) {
                    $weikuan = $wk;
                } else {
                    $weikuan = $weikuan . '、' . $wk;
                }
            }
        }
        $chidao = 0;
        $zaotui = 0;
        $queka = 0;
        $weigui = 0;
        $kuanggong = 0;
        if (!empty($sign) && $sign['orderid'] != -1) {
            if ($sign['monstar'] <= 1 || $sign['aftstar'] <= 1) {
                $queka += 1;
            }
            if ($sign['monstar'] == 3) {
                $chidao += 1;
            }
            if ($sign['aftstar'] == 3) {
                $zaotui += 1;
            }
            if ($sign['monwei'] == 2) {
                $weigui += 1;
            }
            if ($sign['afterwei'] == 2) {
                $weigui += 1;
            }
        }
        if (!empty($sign) && $sign['orderid'] == -1) {
            $kuanggong += 1;
        }
        $dzkhlx = trim($sign['btaddress'] ?? '');
        if (empty($dzkhlx)) {
            $dzkhlx =  $dzkhlx . trim($sign['btname'] ?? '');
        } else {
            $dzkhlx = $dzkhlx . '|' . trim($sign['btname'] ?? '');
        }
        if (empty($dzkhlx)) {
            $dzkhlx =  $dzkhlx . trim($sign['texts'] ?? '');
        } else {
            $dzkhlx =  $dzkhlx . '|' . trim($sign['texts'] ?? '');
        }
        if ($shang['i'] > 0 && $shang['orderid'] == $sign['orderid']) {
            $shang['lianxu'] += 1;
            $shang['chidao'] += $chidao;
            $shang['zaotui'] += $zaotui;
            $shang['queka'] += $queka;
            $shang['weigui'] += $weigui;
            $shang['kuanggong'] += $kuanggong;
            $data[$shang['key']] = [
                'name' => trim($users['account'] ?? ''),
                'date' => $shang['frist'] . ' ~ ' . $i,
                'orderid' => $sign['orderid'],
                'groups' => $groups,
                'address' => trim($sign['addresstext'] ?? ''),
                'address2' => trim($address ?? ''),
                'kehuname' => $kehuname,
                'type' => $type,
                'days' => (float)$shang['lianxu'],
                'weikuan' => trim($weikuan ?? ''),
                'areas' => trim($mianji . $xiu),
                'dpxx' => $dpxx,
                'weigui' => $shang['weigui'],
                'chidao' => $shang['chidao'],
                'zaotui' => $shang['zaotui'],
                'queka' => $shang['queka'],
                'kuanggong' => $shang['kuanggong'],
                'kuayue' => $shang['kuayue'] ?? ''
            ];
        } else {
            $shang['orderid'] = $sign['orderid'];
            $shang['frist'] = $i;
            $shang['lianxu'] = 1;
            $shang['chidao'] = $chidao;
            $shang['zaotui'] = $zaotui;
            $shang['queka'] = $queka;
            $shang['weigui'] = $weigui;
            $shang['kuanggong'] = $kuanggong;
            $shang['kuayue'] = $kuayue ?? '';
            $data[] = [
                'name' => trim($users['account'] ?? ''),
                'date' => $i ?? '',
                'orderid' => $sign['orderid'],
                'groups' => $groups,
                'address' => trim($sign['addresstext'] ?? ''),
                'address2' => trim($address ?? ''),
                'kehuname' => $kehuname,
                'type' => $type,
                'days' => (float)$shang['lianxu'],
                'weikuan' => trim($weikuan ?? ''),
                'areas' => trim($mianji . $xiu),
                'dpxx' => $dpxx,
                'weigui' => $shang['weigui'],
                'chidao' => $shang['chidao'],
                'zaotui' => $shang['zaotui'],
                'queka' => $shang['queka'],
                'kuanggong' => $shang['kuanggong'],
                'kuayue' => $shang['kuayue'] ?? ''
            ];
            $shang['key'] = count($data) - 1;
        }
        $shang['i'] = $i;
    }
    if ($isshengcheng == 2) {
        (new Signexcel())->allowfield(true)->save([
            'user_id' => $users['id'],
            'olddata' => json_encode($data),
            'newdata' => json_encode($data),
            'yeardays' => date('Y-m-01', $time)
        ]);
    }
    return $data;
}

/**
 * 功能：生成二维码
 * @param string $qrData 手机扫描后要跳转的网址
 * @param string $qrLevel 默认纠错比例 分为L、M、Q、H四个等级，H代表最高纠错能力
 * @param string $qrSize 二维码图大小，1－10可选，数字越大图片尺寸越大
 * @param string $savePath 图片存储路径
 * @param string $savePrefix 图片名称前缀
 */
function createQRcode($savePath, $qrData = 'PHP QR Code :)', $qrLevel = 'L', $qrSize = 4, $savePrefix = 'qrcode')
{
    if (!isset($savePath)) return '';
    //设置生成png图片的路径
    $PNG_TEMP_DIR = $savePath;

    //检测并创建生成文件夹
    if (!file_exists($PNG_TEMP_DIR)) {
        mkdir($PNG_TEMP_DIR);
    }
    $filename = $PNG_TEMP_DIR . 'test.jpg';
    $errorCorrectionLevel = 'L';
    if (isset($qrLevel) && in_array($qrLevel, ['L', 'M', 'Q', 'H'])) {
        $errorCorrectionLevel = $qrLevel;
    }
    $matrixPointSize = 4;
    if (isset($qrSize)) {
        $matrixPointSize = min(max((int)$qrSize, 1), 10);
    }
    if (isset($qrData)) {
        if (trim($qrData) == '') {
            die('data cannot be empty!');
        }
        //生成文件名 文件路径+图片名字前缀+md5(名称)+.png
        $filename = $PNG_TEMP_DIR . $savePrefix . md5($qrData . '|' . $errorCorrectionLevel . '|' . $matrixPointSize) . '.jpg';
        //开始生成
        \PHPQRCode\QRcode::png($qrData, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    } else {
        //默认生成
        \PHPQRCode\QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    }
    if (file_exists($PNG_TEMP_DIR . basename($filename))) {
        return basename($filename);
    } else {
        return FALSE;
    }
}


//俩个坐标点之间的距离
function getDistance($lon1, $lat1, $lon2, $lat2, $unit = 2, $decimal = 2)
{

    $EARTH_RADIUS = 6371.004; // 地球半径系数
    $PI = 3.1415926;
    $radLat1 = $lat1 * $PI / 180.0;
    $radLat2 = $lat2 * $PI / 180.0;
    $radLng1 = $lon1 * $PI / 180.0;
    $radLng2 = $lon2 * $PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $distance = $distance * $EARTH_RADIUS * 1000;
    if ($unit == 2) {
        $distance = $distance / 1000;
    }
    return round($distance, $decimal);
}

//生成推荐码
function createOrdersn()
{
    $code = time() . rand(100000, 999999);
    return $code;
}

function reordersn($model)
{
    $code = createOrdersn();
    $row = $model->where('ordersn', $code)->find();
    if ($row) {
        reordersn();
    } else {
        return $code;
    }
}


//生成订单号
function createPayOrdersn()
{
    $code = time() . rand(100000, 999999);
    return $code;
}

function repayorder($model)
{
    $code = createPayOrdersn();
    $row = $model->where('paymentid', $code)->find();
    if ($row) {
        repayorder();
    } else {
        return $code;
    }
}

//生成推荐码
function createorderCode()
{
    $code = rand(10000000, 99999999);
    return $code;
}

function orecode($user)
{
    $code = createorderCode();
    $row = $user->where('code', $code)->find();
    if ($row) {
        orecode();
    } else {
        return $code;
    }
}

//生成推荐码
function createCode()
{
    $code = rand(10000000, 99999999);
    return $code;
}

function recode($user)
{
    $code = createCode();
    $row = $user->where('code', $code)->find();
    if ($row) {
        recode();
    } else {
        return $code;
    }
}

function rsa_asr($rsa, $data = [])
{
    $MAX_DECRYPT_BLOCK = 172;
    $ct = "";
    $str = strlen($data);
    $offSet = 0;
    $endOffSet = $MAX_DECRYPT_BLOCK;
    while ($str - $offSet > 0) {
        if ($str - $offSet > $MAX_DECRYPT_BLOCK) {
            $bufTmp = substr($data, $offSet, $endOffSet);
            $ct .= $rsa->privDecrypt($bufTmp);
        } else {
            $bufTmp = substr($data, $offSet, $str);
            $ct .= $rsa->privDecrypt($bufTmp);
        }
        $offSet += $MAX_DECRYPT_BLOCK;
    }
    return json_decode($ct, true);
}



function unique()
{
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)]
        . strtoupper(dechex(date('m')))
        . date('d') . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    for (
        $a = md5($rand, true),
        $s = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord($a[$f]),
        $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
        $f++
    );
    return $d;
}

//1.数组转xml
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<$key>$val</$key>";
        } else
            $xml .= "<$key><![CDATA[$val]]></$key>";
    }
    $xml .= "</xml>";
    return $xml;
}

//2.xml转数组
function xmlToArray($xml)
{
    $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $arr;
}


/**

 * excel表格导出

 * @param string $fileName 文件名称

 * @param array $headArr 表头名称

 * @param array $data 要导出的数据

 * @author static7  */

function excelExport($fileName = '', $headArr = [], $data = [])
{
    $date = date("Y_m_d", time());
    $fileName .= "_{$date}.xls";
    //创建PHPExcel对象，注意，不能少了\
    $objPHPExcel = new \PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    //设置表头
    $key = 0;
    //print_r($headArr);exit;
    foreach ($headArr as $v) {
        //注意，不能少了。将列数字转换为字母\
        $colum = \PHPExcel_Cell::stringFromColumnIndex($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();

    foreach ($data as $key => $rows) { //行写入
        $span = 0;
        foreach ($rows as $keyName => $value) { // 列写入
            $j = \PHPExcel_Cell::stringFromColumnIndex($span);
            $objActSheet->setCellValue($j . $column, $value);
            $span++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    $objPHPExcel->getActiveSheet()->setTitle($date);
    //设置字体大小
    $objPHPExcel->getDefaultStyle()->getFont()->setSize(14);
    //设置单元格宽度
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
    //设置默认行高
    $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(23);
    //设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); //文件通过浏览器下载
    exit;
}


function api_curl($url, $data = false, $ispost = 0)
{
    $headers = array();
    array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
    curl_setopt($ch, CURLOPT_TIMEOUT, 300);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    if (1 == strpos("$" . $url, "https://")) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if ($ispost) {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        $data = http_build_query($data);
        if ($data) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $data);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    $response = json_decode($response, true);
    return $response;
}


/**
 * Excel导出
 * @param array $title
 * @param array $data
 * @param string $fileName 表名
 * @param bool $bold 列名是否加粗
 * @param bool $returnFile 是否下载
 * @param array $conditions 单元格样式
 * 示例 $conditions = array('field'=>'time_difference','symbol'=>'gt','value'=>0,'style'=>array('font' => array('color' => array('rgb' => 'FF0000'),),));
 * @return bool|string
 * @throws PHPExcel_Exception
 * @throws PHPExcel_Reader_Exception
 * @throws PHPExcel_Writer_Exception
 */
function exportDataToExcel($title = array(), $data = array(), $fileName = '', $bold = true, $returnFile = false, $conditions = array(), $merge_cells = array())
{
    if (empty($title)) {
        return false;
    }

    if (!empty($merge_cells)) {
        $num_arr = array_column($data, $merge_cells['field']);
        $arr = array_count_values($num_arr);
    }
    $objPHPExcel = new PHPExcel();
    $count = count($title);
    $borderarr = array(
        'borders' => array(
            'allborders' => array(                               //allborders  表示全部线框
                'style' => \PHPExcel_Style_Border::BORDER_THIN,   //设置border样式
                'color' => array('argb' => 'FF000000'),          //设置border颜色
            ),
        ),
    );
    for ($i = 0; $i < $count; $i++) {
        $i_name = \PHPExcel_Cell::stringFromColumnIndex($i); //处理列大于26个的方法
        //设置列宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension($i_name)->setWidth($title[$i]['width']);
        //设置列名
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . '1', $title[$i]['title']);
        //列名是否加粗
        if ($bold) {
            $objPHPExcel->getActiveSheet()->getStyle($i_name . '1')->getFont()->setBold(true);
        }
        //设置列名高度
        $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(40);
        //设置居中
        $objPHPExcel->getActiveSheet()->getStyle($i_name . '1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle($i_name . '1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle($i_name . '1')->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->getStyle($i_name . '1')->applyFromArray($borderarr);

        //数据处理
        if ($data) {
            foreach ($data as $key => $item) {
                if (isset($title[$i]['field']) && !empty($item[$title[$i]['field']])) {
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . ($key + 2), $item[$title[$i]['field']]);
                    //添加样式
                    if (!empty($conditions)) {
                        foreach ($conditions as $condition) {
                            if ($condition['field'] == $title[$i]['field']) {
                                // gt 表示 > 大于 egt 表示 >= 大于等于 lt 表示 < 小于 elt 表示 <= 小于等于 eq 表示 = 等于 neq 表示 = 不等于”
                                switch ($condition['symbol']) {
                                    case 'gt':
                                        if ($item[$title[$i]['field']] > $condition['value']) {
                                            $objPHPExcel->getActiveSheet()->getStyle('A' . ($key + 2) . ':BI' . ($key + 2))->applyFromArray($condition['style']);
                                        }
                                        break;
                                    case 'egt':
                                        if ($item[$title[$i]['field']] >= $condition['value']) {
                                            $objPHPExcel->getActiveSheet()->getStyle('A' . ($key + 2) . ':BI' . ($key + 2))->applyFromArray($condition['style']);
                                        }
                                        break;
                                    case 'lt':
                                        if ($item[$title[$i]['field']] < $condition['value']) {
                                            $objPHPExcel->getActiveSheet()->getStyle('A' . ($key + 2) . ':BI' . ($key + 2))->applyFromArray($condition['style']);
                                        }
                                        break;
                                    case 'elt':
                                        if ($item[$title[$i]['field']] <= $condition['value']) {
                                            $objPHPExcel->getActiveSheet()->getStyle('A' . ($key + 2) . ':BI' . ($key + 2))->applyFromArray($condition['style']);
                                        }
                                        break;
                                    case 'eq':
                                        if ($item[$title[$i]['field']] == $condition['value']) {
                                            $objPHPExcel->getActiveSheet()->getStyle('A' . ($key + 2) . ':BI' . ($key + 2))->applyFromArray($condition['style']);
                                        }
                                        break;
                                    case 'neq':
                                        if ($item[$title[$i]['field']] != $condition['value']) {
                                            $objPHPExcel->getActiveSheet()->getStyle('A' . ($key + 2) . ':BI' . ($key + 2))->applyFromArray($condition['style']);
                                        }
                                        break;
                                    default:
                                }
                            }
                        }
                    }
                }

                if (!empty($merge_cells)) {
                    //纵向合并
                    foreach ($arr as $kk => $vv) {
                        if ($vv > 1) {
                            $keys = array_keys($num_arr, $kk);
                            $end = $keys[count($keys) - 1] + 2;
                            $start = $end - $vv + 1;
                            //合并排除字段
                            if (!empty($merge_cells['exclude_field']) && !in_array($title[$i]['field'], $merge_cells['exclude_field'])) {
                                $objPHPExcel->getActiveSheet()->mergeCells($i_name . $start . ":" . $i_name . $end);
                            }
                            //合并选择字段
                            if (!empty($merge_cells['include_field']) && in_array($title[$i]['field'], $merge_cells['include_field'])) {
                                $objPHPExcel->getActiveSheet()->mergeCells($i_name . $start . ":" . $i_name . $end);
                            }
                        }
                    }
                }
                $objPHPExcel->getActiveSheet()->getStyle($i_name . ($key + 2))->applyFromArray($borderarr);
                //设置居中
                $objPHPExcel->getActiveSheet()->getStyle($i_name . ($key + 2))->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $objPHPExcel->getActiveSheet()->getStyle($i_name . ($key + 2))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getActiveSheet()->getStyle($i_name . ($key + 2))->getAlignment()->setWrapText(true);
            }
        }
    }
    $objPHPExcel->getActiveSheet()->setTitle('Simple');
    $objPHPExcel->setActiveSheetIndex(0);
    $fileName = $fileName ? $fileName : date("Ymd", time());
    if ($returnFile) {
        // $dirPath = ROOT_PATH . 'excelimg'; //注意要设置为绝对路径
        $newFileName = $fileName;
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $newFileName . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        return $newFileName;
    } else {
        // excel头参数
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '(' . date('m月d日H时i分s秒导') . ')' . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); //excel5为xls格式，excel2007为xlsx格式
        $objWriter->save('php://output');
        exit;
    }
}
